import { defineStore } from 'pinia'

export const useChatStore = defineStore('chat', {
  state: () => ({
    conversations: [],
    currentConversationId: null,
    loading: false,
    sseConnection: null,
    isThinking: false, // 深度思考状态
    thinkingDepth: 1, // 新增思考深度级别
    thinkingPrompt: '' // 新增思考提示词
  }),
  actions: {
    setThinkingDepth(level) {
      this.thinkingDepth = Math.min(Math.max(1, level), 3);
    },
    setThinkingPrompt(prompt) {
      this.thinkingPrompt = prompt;
    },
    newConversation() {
      const newConvo = {
        id: Date.now(),
        title: '新对话',
        messages: [],
        lastUpdated: new Date().toISOString()
      }
      this.conversations.unshift(newConvo)
      this.currentConversationId = newConvo.id
    },
    setLoading(status) {
      this.loading = status;
    },

    toggleThinking() {
      this.isThinking = !this.isThinking;
      if (this.isThinking) {
        this.connectSSE();
        this.sseConnection.addEventListener('thinking_start', (event) => {
          const { depth } = JSON.parse(event.data);
          this.setLoading(true);
          this.setThinkingDepth(depth);
        });
        this.sseConnection.addEventListener('thinking_progress', (event) => {
          const { progress } = JSON.parse(event.data);
          this.loadingMessage = `深度思考中 (${progress}%)...`;
        });
        this.sseConnection.addEventListener('thinking_end', () => {
          this.setLoading(false);
          this.loadingMessage = '';
        });
      } else {
        this.closeSSE();
      }
    },

    addMessage(message) {
      const convo = this.conversations.find(c => c.id === this.currentConversationId)
      if (convo) {
        convo.messages.push(message)
        convo.lastUpdated = new Date().toISOString()
        
        // 发送消息到SSE接口
        if (this.sseConnection) {
          this.sseConnection.send(JSON.stringify({
            conversationId: this.currentConversationId,
            message: message.content
          }));
        }
      }
    },
    
    // 初始化SSE连接
    connectSSE() {
      this.sseConnection = new EventSource('/api/sse-chat');
      
      this.sseConnection.onmessage = (event) => {
        const response = JSON.parse(event.data);
        this.addMessage({
          role: 'assistant',
          content: this.thinkingDepth === 3 ? `【深度分析】${response.content}` : response.content,
          timestamp: new Date().toISOString()
        });
      };
      
      this.sseConnection.onerror = (err) => {
        console.error('SSE error:', err);
        this.closeSSE();
      };
    },
    
    // 关闭SSE连接
    closeSSE() {
      if (this.sseConnection) {
        this.sseConnection.close();
        this.sseConnection = null;
      }
    },

    deleteConversation(conversationId) {
      this.conversations = this.conversations.filter(c => c.id !== conversationId)
      if (this.currentConversationId === conversationId) {
        this.currentConversationId = this.conversations[0]?.id || null
      }
    }
  },
  getters: {
    currentConversation: (state) => 
      state.conversations.find(c => c.id === state.currentConversationId)
  }
})
